﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SubSonic;
using ExtAspNet;


namespace TCMSystem.admin
{
    public partial class user : PageBase
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Module

        /// <summary>
        /// 当前页面所属的模块
        /// </summary>
        public override ModuleType Module
        {
            get
            {
                return ModuleType.CoreUser;
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            // 权限检查
            CheckPowerEditWithButton(btnChangeEnableUsers);
            CheckPowerDeleteWithButton(btnDeleteSelected);
            CheckPowerNewWithButton(btnNew);
            


            ResolveDeleteButtonForGrid(btnDeleteSelected, Grid1);

            ResolveEnableStatusButtonForGrid(btnEnableUsers, Grid1, true);
            ResolveEnableStatusButtonForGrid(btnDisableUsers, Grid1, false);

            btnNew.OnClientClick = Window1.GetShowReference("~/admin/user_new.aspx", "新增用户");

            //// 默认的排序列和排序方向
            //Grid1.SortColumnIndex = 0;
            //Grid1.SortDirection = "DESC";

            // 每页记录数
            Grid1.PageSize = TblMstConfigHelper.PageSize;

            //// 点击删除按钮时，至少选中一项
            //ResolveDeleteGridItem(btnDeleteSelected, Grid1);

            BindGrid();
        }

        private void ResolveEnableStatusButtonForGrid(MenuButton btn, Grid grid, bool enabled)
        {
            string enabledStr = "启用";
            if (!enabled)
            {
                enabledStr = "禁用";
            }
            btn.OnClientClick = grid.GetNoSelectionAlertInParentReference("请至少应该选择一项记录！");
            btn.ConfirmText = String.Format("确定要{1}选中的<span class=\"highlight\"><script>{0}</script></span>项记录吗？", grid.GetSelectCountReference(), enabledStr);
            btn.ConfirmTarget = ExtAspNet.Target.Top;
        }

        private void BindGrid()
        {
            SqlQuery q = new Select().From<TblMstUser>();
            q.Where("1").IsEqualTo("1");

            // 在职务名称中搜索
            string searchText = ttbSearchMessage.Text.Trim();
            if (!String.IsNullOrEmpty(searchText))
            {
                q.And(TblMstUser.NameColumn).ContainsString(searchText);
            }

            // 过滤启用状态
            if (rblEnableStatus.SelectedValue != "all")
            {
                q.And(TblMstUser.EnabledColumn).IsEqualTo(rblEnableStatus.SelectedValue == "enabled" ? true : false);
            }

            // 在查询添加之后，排序和分页之前获取总记录数
            // Grid1总共有多少条记录
            Grid1.RecordCount = q.GetRecordCount();

            // 排列
            q.OrderBys.Add(GetSortExpression(Grid1, TblMstUser.Schema));

            // 数据库分页
            q.Paged(Grid1.PageIndex + 1, Grid1.PageSize);
            TblMstUserCollection items = q.ExecuteAsCollection<TblMstUserCollection>();

            Grid1.DataSource = items;
            Grid1.DataBind();
        }

        #endregion

        #region Events

        protected void ttbSearchMessage_Trigger2Click(object sender, EventArgs e)
        {
            ttbSearchMessage.ShowTrigger1 = true;
            BindGrid();
        }

        protected void ttbSearchMessage_Trigger1Click(object sender, EventArgs e)
        {
            ttbSearchMessage.Text = String.Empty;
            ttbSearchMessage.ShowTrigger1 = false;
            BindGrid();
        }

        protected void Grid1_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            CheckPowerEditWithWindowField(Grid1, "editField");
            CheckPowerDeleteWithLinkButtonField(Grid1, "deleteField");
            CheckPowerWithWindowField(ModulePowerType.CoreUser_ChangePassword, Grid1, "changePasswordField");
        }
        

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortColumnIndex = e.ColumnIndex;
            BindGrid();
        }

        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPowerDelete())
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<int> ids = GetSelectedDataKeyIDs(Grid1);

            // 执行数据库操作
            new Delete().From<TblMstUser>()
                 .Where(TblMstUser.IdColumn).In(ids)
                 .Execute();

            // 清空当前选中的项
            Grid1.SelectedRowIndexArray = null;

            // 重新绑定表格
            BindGrid();
        }

        protected void btnEnableUsers_Click(object sender, EventArgs e)
        {
            SetSelectedUsersEnableStatus(true);
        }

        protected void btnDisableUsers_Click(object sender, EventArgs e)
        {
            SetSelectedUsersEnableStatus(false);
        }


        private void SetSelectedUsersEnableStatus(bool enabled)
        {
            // 在操作之前进行权限检查
            if (!CheckPowerEdit())
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<int> ids = GetSelectedDataKeyIDs(Grid1);

            // 执行数据库操作
            TblMstUserCollection users = new Select().From<TblMstUser>()
                .Where(TblMstUser.IdColumn).In(ids)
                .ExecuteAsCollection<TblMstUserCollection>();
            foreach (TblMstUser user in users)
            {
                user.Enabled = enabled;
            }
            users.BatchSave();

            // 清空当前选中的项
            Grid1.SelectedRowIndexArray = null;

            // 重新绑定表格
            BindGrid();
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            object[] values = Grid1.DataKeys[e.RowIndex];
            int id = Convert.ToInt32(values[0]);
            string name = Convert.ToString(values[1]);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                if (!CheckPowerDelete())
                {
                    CheckPowerFailWithAlert();
                    return;
                }

                if (name == "admin")
                {
                    Alert.ShowInTop("不能删除名为admin的用户，这是默认的系统管理员。");
                }
                else
                {
                    TblMstUser.Delete(id);

                    BindGrid();
                }
            }
            //else if (e.CommandName == "Enabled")
            //{
            //    bool rowChecked = Convert.ToBoolean(Grid1.Rows[e.RowIndex].States[e.ColumnIndex]);

            //    TblMstUser item = TblMstUser.FetchByID(id);
            //    item.Enabled = rowChecked;
            //    item.Save(User.Identity.Name);

            //    BindGrid();
            //}

        }

        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void rblEnableStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGrid();
        }


        #endregion

    }
}
